import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/login/model/login_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 重置手机号登录密码
class ResetPasswordPage extends ConsumerStatefulWidget {
  const ResetPasswordPage({required this.uuid, required this.phone, super.key});

  final String uuid;
  final String phone;

  @override
  ConsumerState<ResetPasswordPage> createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends ConsumerState<ResetPasswordPage> {
  final _formKey = GlobalKey<FormState>();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final textColor = Colors.black;

  /// 输入框间距
  final double _inputMargin = 12;

  /// 修改手机号密码
  _changePhoneOrAgentPassword() async {
    final changePasswordData = {'uuid': widget.uuid, 'phone': widget.phone, 'password': _passwordController.text};
    ToastUtils.showLoading();
    var res =
        await post<LoginResp, LoginResp>('/app/user/passwordReset', data: changePasswordData, decodeType: LoginResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        _changePasswordSuccess(resp.data!);
      } else {
        ToastUtils.showToast(resp.msg ?? '修改失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('修改密码失败 code: $code msg: $msg');
    });
  }

  /// 修改密码成功
  _changePasswordSuccess(LoginData loginData) {
    ToastUtils.showToast('密码已修改');
    // 登录成功，跳转到主页
    SpUtil.putObject('loginData', loginData);
    SpUtil.putBool('isLogin', true);
    ref.read(userTypeProvider.notifier).state = UserTypeEnum.fromValue(loginData.type!);
    context.go(RouterManager.home);
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        iconTheme: IconThemeData(color: AppTheme.themeConfig.primaryTextColor),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 标题
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(
                left: 20,
              ),
              child: const Text(
                '修改密码',
                style: TextStyle(
                  fontSize: 24,
                ),
              ),
            ),
            // 提示
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(
                left: 20,
              ),
              child: Text(
                '8-16位英文字母、数字、字符组合，不能是纯数字',
                style: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
              ),
            ),
            const SizedBox(
              height: 60,
            ),
            // 表单
            Container(
              margin: const EdgeInsets.only(left: 20, right: 20),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _passwordController,
                      obscureText: true,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请输入新密码",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        // 调整内边距
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入新密码';
                        }
                        return null;
                      },
                    ),
                    SizedBox(
                      height: _inputMargin,
                    ),
                    TextFormField(
                      controller: _confirmPasswordController,
                      obscureText: true,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请确认新密码",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        // 调整内边距
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请确认新密码';
                        }
                        if (value != _passwordController.text) {
                          return '两次输入的密码不一致';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    // 登录按钮
                    SizedBox(
                      width: double.infinity,
                      height: 50,
                      child: ElevatedButton(
                        onPressed: () {
                          // 校验表单
                          if (_formKey.currentState!.validate()) {
                            // 验证通过提交数据
                            _changePhoneOrAgentPassword();
                          }
                        },
                        style: ButtonStyle(
                          shape: MaterialStateProperty.all(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(32),
                            ),
                          ),
                          backgroundColor: MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
                        ),
                        child: const Text(
                          "确定",
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
